package com.example.statistics.ui.purchase

import android.graphics.Color
import android.graphics.Typeface
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.style.AbsoluteSizeSpan
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.widget.TextView
import com.example.statistics.R
import com.example.statistics.bean.ExchangeRate
import com.example.statistics.bean.FuturesFeeBean
import com.example.statistics.bean.PurchaseAgentBean
import com.example.statistics.bean.PurchaseProductBean
import com.example.statistics.common.BaseLoadingListActivity
import com.example.statistics.ex.*
import com.example.statistics.net.UrlConfig
import com.example.statistics.utils.Constants
import com.jhj.slimadapter.SlimAdapter
import com.jhj.slimadapter.holder.ViewInjector
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.textColor
import java.math.BigDecimal
import java.util.*

class PurchaseEstimateListActivity : BaseLoadingListActivity<PurchaseProductBean>() {

    val time = Date().time
    private val dayMillisecond = 24 * 60 * 60 * 1000
    private var agent: PurchaseAgentBean? = null
    private var financingRate = 0.0//

    private var rateList: MutableList<ExchangeRate>? = null

    override val title: String
        get() = agent?.agent ?: "采购"

    override val itemLayoutRes: Int
        get() = R.layout.list_item_purchase_product_prepary

    override val url: String
        get() = UrlConfig.PURCHASE_PRODUCT_LIST_DATA

    override val httpParams: MutableList<Pair<String, String>>
        get() = mutableListOf("agentId" to (agent?.id ?: 0).toString())

    override val inputSearch: Boolean
        get() = true

    override val inputSearchFunc: (PurchaseProductBean, String) -> Boolean = { bean, str ->
        bean.productName.contains(str) || bean.containerNo.contains(str) || bean.contractNo.contains(str)
    }

    override fun initialize() {
        super.initialize()
        agent = intent.getSerializableExtra(Constants.DATA) as PurchaseAgentBean?
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        when (agent?.id) {
            1 -> financingRate = 0.075 //新协航
            2 -> financingRate = 0.07.mulEx(1.03, 6).toDouble()//泽厚
            3 -> financingRate = 0.075//国晟
            4 -> financingRate = 0.076//翰强
        }
        httpGet<MutableList<ExchangeRate>>(UrlConfig.PURCHASE_RATE_LIST) {
            rateList = it
        }

    }

    override fun formatList(dataList: MutableList<PurchaseProductBean>): MutableList<PurchaseProductBean> {
        var list = dataList.filter { !it.futuresFeeList.isNullOrEmpty() && it.futuresFeeList?.find { it.feeType.contains("尾款") } != null }
        list = list.sortedWith(compareBy({ it.shippingInfo?.deliveryDate }, { it.shippingInfo?.arrivalDate }))
        return list.toMutableList()
    }

    override fun onResume() {
        super.onResume()
        refresh()
    }


    override fun itemViewConvert(adapter: SlimAdapter, injector: ViewInjector, bean: PurchaseProductBean, position: Int) {

        val feeMay = mutableMapOf<String, FuturesFeeBean>()
        bean.futuresFeeList?.forEach {
            feeMay[it.feeType] = it
        }

        //货款
        val deposit = feeMay["实际定金"] ?: feeMay["预付定金"] ?: feeMay["预估定金"]
        val balance = feeMay["实际尾款"] ?: feeMay["预付尾款"] ?: feeMay["预估尾款"]
        val margin = feeMay["实际保证金"] ?: feeMay["预付保证金"]
        val portInfo = bean.shippingInfo

        val futuresFee = when (bean.productTotalPrice) {
            deposit?.dollar.addEx(balance?.dollar).addEx(margin?.dollar).toDouble() -> {
                deposit?.totalFee.addEx(balance?.totalFee).addEx(margin?.totalFee).toDouble()
            }
            deposit?.dollar.addEx(balance?.dollar).toDouble() -> {
                deposit?.totalFee.addEx(balance?.totalFee).toDouble()
            }
            else -> {
                deposit?.totalFee.addEx(balance?.totalFee).toDouble()
            }
        }


        //税款
        val taxFee = if (bean.taxFee != null && bean.taxFee?.totalFee != 0.0) {
            bean.taxFee?.totalFee ?: 0.0
        } else {
            val rate =/* rateList?.find {
                it.date == (portInfo?.arrivalDate
                        ?: portInfo?.warehousingDate
                        ?: balance?.date)?.substring(0, 7)
            }?.rate ?: */7.0
            val tariff = if (bean.productName.contains("肚")) 0.20 else 0.12
            val tariffFee = bean.productTotalPrice.mulEx(rate).mulEx(tariff)
            val valueAddedTax = (tariffFee.add(bean.productTotalPrice.mulEx(rate, 2))).mulEx(0.09)
            tariffFee.addEx(valueAddedTax).toDouble()
        }

        //融资利息
        val financingBalance = when (agent?.id) {
            1 -> {//带手续费但是和保证金没关系
                feeMay["预付尾款"]?.totalFee
                        .subEx((feeMay["实际尾款"] ?: feeMay["预估尾款"])?.totalFee).abs()
            }
            4 -> { //带手续费
                val depositDifference = feeMay["预付定金"]?.totalFee
                        .subEx(feeMay["实际定金"]?.totalFee)//定金差额
                val balanceDifference = feeMay["预付尾款"]?.totalFee
                        .addEx(feeMay["预付保证金"]?.totalFee)
                        .subEx((feeMay["实际尾款"] ?: feeMay["预估尾款"])?.totalFee)
                        .subEx(feeMay["实际保证金"]?.totalFee).abs()//尾款差额

                balanceDifference.addEx(depositDifference).abs()
            }
            else -> { //不带手续费
                val depositDifference = feeMay["预付定金"]?.rmb
                        .subEx(feeMay["实际定金"]?.rmb)//定金差额
                val balanceDifference = feeMay["预付尾款"]?.rmb
                        .addEx(feeMay["预付保证金"]?.rmb)
                        .subEx((feeMay["实际尾款"] ?: feeMay["预估尾款"])?.rmb)
                        .subEx(feeMay["实际保证金"]?.rmb).abs()//尾款差额

                balanceDifference.addEx(depositDifference).abs()
            }
        }

        var financingFee = BigDecimal(0)
        if (bean.financingFeeList != null) {
            financingFee = bean.financingFeeList?.sumEx {
                it.financingInterest.orEmpty()
            } ?: BigDecimal(0)
        } else {
            taxFee.let {
                val startDate = bean.taxFee?.date ?: portInfo?.arrivalDate.goTimeFormat()
                val startTimes = startDate.parse()?.time ?: time
                val days = (time - startTimes) / dayMillisecond + 1
                val interest = days.mulEx(taxFee, 6).mulEx(financingRate, 6).divEx(360, 2).toDouble()
                financingFee = financingFee.addEx(interest)
            }
            financingBalance.let {
                val startTimes = balance?.date.parse()?.time ?: time
                val days = (time - startTimes) / dayMillisecond + 1
                val interest = days.mulEx(it, 6).mulEx(financingRate, 6).divEx(360, 2).toDouble()
                financingFee = financingFee.addEx(interest)
            }
        }


        //清关费用:没有出库按14500计算
        var clearanceFee = 0.0
        if (!portInfo?.deliveryDate.goTimeFormat().isNullOrBlank()) {
            bean.clearanceFeeList?.forEach {
                clearanceFee = it.value.addEx(clearanceFee).toDouble()
            }
        } else {
            clearanceFee = 14500.0
        }


        //仓储费
        val pound = 2.2046226
        var storageFee = 0.0
        portInfo?.warehousingDate.goTimeFormat()?.parse()?.time?.let {
            val days = (time - it) / dayMillisecond + 1
            val fee = when {
                //上海
                portInfo?.coldStorage?.contains("创节") == true -> 3.8    //新协航
                portInfo?.coldStorage?.contains("誉尚") == true -> 3.5    //新协航（周天休息）
                portInfo?.coldStorage?.contains("御驰") == true -> 3.6    //新协航
                portInfo?.coldStorage?.contains("中丹宝") == true -> 3.6    //新协航
                portInfo?.coldStorage?.contains("紫鸿") == true -> 3.6    //新协航
                portInfo?.coldStorage?.contains("顺凯") == true -> 3.5    //翰强
                portInfo?.coldStorage?.contains("锦恒") == true -> 3.5    //泽厚
                //盐田
                portInfo?.coldStorage?.contains("友信") == true -> 3.4    //新协航、翰强
                //天津
                portInfo?.coldStorage?.contains("晟邦") == true -> 3.5    //新协航
                portInfo?.coldStorage?.contains("泰达行") == true -> 3.5  //翰强、国晟
                portInfo?.coldStorage?.contains("金三") == true -> 3.0    //泽厚
                portInfo?.coldStorage?.contains("达乐成") == true -> 3.5  //新协航
                portInfo?.coldStorage?.contains("华亿") == true -> 3.0    //新协航
                portInfo?.coldStorage?.contains("海联") == true -> 3.5    //新协航
                else -> 3.5
            }
            storageFee = if (bean.weightUnit == "磅") {
                days.mulEx(bean.productWeight).divEx(pound).mulEx(fee).divEx(1000).toDouble()
            } else {
                days.mulEx(bean.productWeight).mulEx(fee).divEx(1000).toDouble()
            }

        }

        val totalFee = if (portInfo?.deliveryDate.goTimeFormat() == null) {
            futuresFee.addEx(taxFee).addEx(clearanceFee).addEx(financingFee).addEx(storageFee)
        } else {
            bean.settlementFeeList?.sumEx { it.amount }
        }


        injector.with<TextView>(R.id.tv_des) {
            val span = SpannableStringBuilder()
            var text = bean.productName
            var start = 0
            var end = text.length
            span.append(text).apply {
                setSpan(StyleSpan(Typeface.BOLD), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            }

            text = "（${bean.contractNo} ${portInfo?.port}）"
            start = end
            end = end.addEx(text.length).toInt()

            span.append(text).apply {
                setSpan(ForegroundColorSpan(Color.GRAY), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
                setSpan(AbsoluteSizeSpan(35), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            }


            text = if (bean.weightUnit.contains("磅")) {
                val weight = bean.productWeight.divEx(pound)
                "预估价:￥${totalFee.divEx(weight, 6).mulEx(10)}"
            } else {
                "预估价:￥${totalFee.divEx(bean.productWeight).mulEx(10)}"
            }

            start = end
            end = end.addEx(text.length).toInt()
            span.append(text).apply {

            }

            var textColor = getResColor(R.color.gray)
            when {
                portInfo?.deliveryDate.goTimeFormat() != null -> {
                    text = "（已出）"
                    textColor = getResColor(R.color.dark_cyan)
                }
                portInfo?.arrivalDate.goTimeFormat() != null || portInfo?.warehousingDate.goTimeFormat() != null -> {
                    text = "（已到）"
                    textColor = getResColor(R.color.lime_green)
                }
                else -> {
                    text = "（即到）"
                }
            }
            start = end
            end = end.addEx(text.length).toInt()
            span.append(text).apply {
                setSpan(AbsoluteSizeSpan(35), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
                setSpan(ForegroundColorSpan(textColor), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            }

            it.textColor = textColor
            it.text = span
        }.clicked {
            startActivity<PurchaseFuturesProductActivity>(
                    Constants.PURCHASE_PRODUCT_ID to bean.ID,
                    Constants.TITLE to bean.factoryNo + bean.productName
            )
        }
    }
}